#include "pwm.hpp"

GPIO_InitTypeDef pwm_set::GPIO_InitStructure;
TIM_TimeBaseInitTypeDef pwm_set::TIM_InitStructure;
TIM_OCInitTypeDef pwm_set::TIM_OCInitStructure;

void pwm_set::PWM_init_general(u16 arr, u16 psc)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOB, ENABLE);
    PWM_GPIO_init();
    // GPIO_PinRemapConfig(GPIO_Remap_TIM4, ENABLE);
    PWM_TIM_init(arr, psc);
    PWM_TIM_OCInit();
    TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable);
    TIM_Cmd(TIM4, ENABLE);
}

void pwm_set::PWM_GPIO_init()
{
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void pwm_set::PWM_TIM_init(u16 arr, u16 psc)
{

    TIM_InitStructure.TIM_Period = arr;                     //设置重装值
    TIM_InitStructure.TIM_Prescaler = psc - 1;              //设置分频系数
    TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
    TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;     //时钟的分频因子，起到了一点点的延时作用，一般设为TIM_CKD_DIV1
    TIM_TimeBaseInit(TIM4, &TIM_InitStructure);
}
void pwm_set::PWM_TIM_OCInit()
{
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //设置有效值为高
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OC2Init(TIM4, &TIM_OCInitStructure);
}